define(['text!html/profile.html', 'css!styles/profile.css', 'js/navigationManager', 'js/bookingsPresenter', 'js/serverWrapper', 'knockoutjs'], function (template, _style, navigationManager, bookingsPresenter, serverWrapper, ko) {
    return new function () {
        var presenter = this;

        var authenticationPresenterPromise = curl('js/authenticationPresenter');
        function viewModel(authenticationPresenter) {
            var self = this;
            var profile = authenticationPresenter.user;

            serverWrapper
                .userTotalCost(authenticationPresenter.getUserID())
                .success(function (result) {
                    self.totalCost(result.total_cost);
                });

            self.name = ko.observable(profile.first_name + ' ' + profile.last_name);
            self.email = ko.observable(profile.email_address);
            self.registrationDate = ko.observable(profile.registration_date);
            self.address = ko.observable(profile.address);
            self.totalCost = ko.observable(0);
            self.failed = ko.observable(false);

            self.bookingsClick = function () {
                var onFailure = function () {
                    self.failed(true);
                };

                serverWrapper
                    .userBookings(authenticationPresenter.getUserID())
                    .success(function (result) {
                        if (result) {
                            bookingsPresenter.bind(result);
                        }
                        else {
                            onFailure();
                        }
                    })
                    .error(onFailure);
            };

            self.logoff = function () {
                authenticationPresenterPromise.then(function (authenticationPresenter) {
                    authenticationPresenter.logoff();
                });
            };
        }

        presenter.bind = function () {
            authenticationPresenterPromise.then(function (authenticationPresenter) {
                navigationManager.load('profile', template, new viewModel(authenticationPresenter));
            });
        };
    };
});